package Begin;

/**
 * @Description:学习线程安全的代码，其中synchronized能够保障原子性,原子性说的就是同一件事情一次只能有一个线程在做，防止产生冲突
 * volatile保证的是内存可见性
 * @Author:AMark
 * @Date: 10/26/2023
 */
public class ThreadSafety {
    static class Counter {
        public int count = 0;
        void increase() {
            count++;
        }
    }
    public static void main(String[] args) throws InterruptedException{
        final Counter counter = new Counter();

        Thread t1 = new Thread(() -> {
           for (int i = 0; i < 50000; i++) {
               counter.increase();
           }
        });
        Thread t2 = new Thread(() -> {
           for (int i = 0; i < 50000; i++) {
               counter.increase();
           }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println(counter.count);
        }
    }

